import requests

from urllib import parse
import os
from urllib import request
import threading
from queue import Queue

# 多线程下载王者荣耀壁纸
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
    'referer': 'https://pvp.qq.com/',
}


def exact_url(data):
    image_url_list = []
    for i in range(1, 9):
        image_url = parse.unquote(data['sProdImgNo_{}'.format(i)]).replace('200', '0')
        image_url_list.append(image_url)
    return image_url_list


# 生产者线程
class Producer(threading.Thread):
    def __init__(self, page_queue, image_url_queue):
        super().__init__()
        self.page_queue = page_queue
        self.image_url_queue = image_url_queue

    def run(self):
        while not self.page_queue.empty():
            page_url = self.page_queue.get()
            resp = requests.get(page_url, headers=headers)
            json_data = resp.json()
            d = {}
            data_list = json_data['List']
            for data in data_list:
                image_url_list = exact_url(data)
                sProdName = parse.unquote(data['sProdName'])
                d[sProdName] = image_url_list
            for key in d:
                dirpath = os.path.join('image', key.strip(' '))
                os.makedirs(dirpath, exist_ok=True)
                for index, image_url in enumerate(d[key]):
                    # 生产图片的url
                    self.image_url_queue.put(
                        {'image_path': os.path.join(dirpath, f'{index + 1}.jpg'), 'image_url': image_url})


# 消费者线程
class Customer(threading.Thread):
    def __init__(self, image_url_queue):
        super().__init__()
        self.image_url_queue = image_url_queue

    def run(self):
        while True:
            try:
                image_obj = self.image_url_queue.get(timeout=20)
                try:
                    request.urlretrieve(image_obj['image_url'], image_obj['image_path'])
                    print('{}下载完毕'.format(image_obj['image_url']))
                except:
                    print('{}下载出错'.format(image_obj['image_url']))
            except:
                break


def start():
    page_queue = Queue(22)
    image_url_queue = Queue(10000)
    for i in range(0, 22):
        page_url = f'https://apps.game.qq.com/cgi-bin/ams/module/ishow/V1.0/query/workList_inc.cgi?activityId=2735&sVerifyCode=ABCD&sDataType=JSON&iListNum=20&totalpage=0&page={i}&iOrder=0&iSortNumClose=1&iAMSActivityId=51991&_everyRead=true&iTypeId=2&iFlowId=267733&iActId=2735&iModuleId=2735&_=1747572781165'
        # print(page_url)
        page_queue.put(page_url)
    # 创建生产者对象
    for i in range(5):
        t = Producer(page_queue, image_url_queue)
        t.start()
    # 创建消费者对象
    for i in range(10):
        c = Customer(image_url_queue)
        c.start()


if __name__ == '__main__':
    start()
